import { useState,useRef } from 'react';

/**
 * 函数防抖
 * @param func 执行函数 
 * @param duration 防抖时间
 */
export const useDebounce = (func: Function | undefined, duration: number = 1000) => {
  /** timeout返回的时间对象 */
  const timer = useRef<any>(null);
  /** 防抖时间 */
  const [delayTime,setDelayTime] = useState<number>(duration);
  /** 防抖函数 */
  const debounceFunc = (...args: Array<any>)=>{
    if(timer.current){
        clearTimeout(timer.current);
        timer.current = null;
    }
    timer.current = setTimeout(() => {
        func(...args);
    }, delayTime);
  }
  /** 清除防抖函数 */
  const clearDebounceFunc = ()=>{
    setDelayTime(0);
  }
  return {debounceFunc,clearDebounceFunc}
}